﻿using System;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace ProjectHT.YKDGVB2012.Core.Membership.Common

{
    public static class MemberShipCommon
    {
        #region Define
        //defind Column Name
        public static readonly string LinkTitle = "LinkTitle";
        public static readonly string LinkTitleNoMenu = "LinkTitleNoMenu";
        public static readonly string Title = "Title";
        public static readonly string LastNamePhonetic = "LastNamePhonetic";
        public static readonly string FirstNamePhonetic = "FirstNamePhonetic";
        public static readonly string FirstName = "FirstName";
        public static readonly string FullName = "FullName";
        public static readonly string Sex = "Sex";
        public static readonly string Bod = "BOD";
        public static readonly string YahooChat = "YahooChat";
        public static readonly string SkypeChat = "SkypeChat";
        public static readonly string UserName = "UserName";
        public static readonly string Email = "Email";
        public static readonly string Company = "Company";
        public static readonly string CompanyPhonetic = "CompanyPhonetic";
        public static readonly string JobTitle = "JobTitle";
        public static readonly string WorkPhone = "WorkPhone";
        public static readonly string HomePhone = "HomePhone";
        public static readonly string CellPhone = "CellPhone";
        public static readonly string WorkFax = "WorkFax";
        public static readonly string WorkAddress = "WorkAddress";
        public static readonly string WorkCity = "WorkCity";
        public static readonly string WorkState = "WorkState";
        public static readonly string WorkZip = "WorkZip";
        public static readonly string WorkCountry = "WorkCountry";
        public static readonly string WebPage = "WebPage";
        public static readonly string Comments = "Comments";
        public static readonly string Password = "Password";
        public static readonly string PasswordQuestion = "PasswordQuestion";
        public static readonly string PasswordReminderAnswer = "PasswordReminderAnswer";
        public static readonly string IsApproved = "isApproved";
        public static readonly string IsRootAccount = "IsRootAccount";
        public static readonly string IsLockedOut = "isLockedOut";
        public static readonly string LastActivityDate = "lastActivityDate";
        public static readonly string LastLockedOutDate = "lastLockedOutDate";
        public static readonly string LastLoginDate = "lastLoginDate";
        public static readonly string LastPasswordChangeDate = "lastPasswordChangeDate";
        public static readonly string CreationDate = "CreationDate";
        public static readonly string Role = "Role";
        public static readonly string ListName = "SiteMembers";
        public static readonly string UserId = "UserID";
        #endregion

        #region Method
        /// <summary>
        /// Create SharePoint List
        /// </summary>
        /// <param name="site">SPSite object</param>
        public static void CreateList(SPSite site)
        {
            
                var spweb = site.OpenWeb();
                var collist = spweb.Lists;
                var listId = collist.Add(ListName, ListName, SPListTemplateType.CustomGrid);

                collist[listId].Fields.Add(LastNamePhonetic, SPFieldType.Text, false);
                var column1 = (SPFieldText) collist[listId].Fields[LastNamePhonetic];
                column1.Hidden = true;
                column1.StaticName = LastNamePhonetic;
                column1.Update();

                collist[listId].Fields.Add(FirstName, SPFieldType.Text, false);
                var column2 = (SPFieldText) collist[listId].Fields[FirstName];
                column2.StaticName = FirstName;
                column2.Update();

                collist[listId].Fields.Add(Bod, SPFieldType.Text, false);
                var brith = (SPFieldText)collist[listId].Fields[Bod];
                brith.StaticName = Bod;
                brith.Update();

                collist[listId].Fields.Add(IsRootAccount, SPFieldType.Boolean, false);
                var isRootAccount = (SPFieldBoolean)collist[listId].Fields[IsRootAccount];
                isRootAccount.StaticName = IsRootAccount;                
                isRootAccount.Update();

                collist[listId].Fields.Add(Sex, SPFieldType.Text, false);
                var sex = (SPFieldText)collist[listId].Fields[Sex];
                sex.StaticName = Sex;
                sex.Update();

                collist[listId].Fields.Add(YahooChat, SPFieldType.Text, false);
                var yahooChat = (SPFieldText)collist[listId].Fields[YahooChat];
                yahooChat.StaticName = YahooChat;
                yahooChat.Update();

                collist[listId].Fields.Add(SkypeChat, SPFieldType.Text, false);
                var skypeChat = (SPFieldText)collist[listId].Fields[SkypeChat];
                skypeChat.StaticName = SkypeChat;
                skypeChat.Update();

                collist[listId].Fields.Add(UserName, SPFieldType.Text, false);
                var userName = (SPFieldText)collist[listId].Fields[UserName];
                userName.StaticName = UserName;           
                userName.Update();

                collist[listId].Fields.Add(FirstNamePhonetic, SPFieldType.Text, false);
                var column3 = (SPFieldText) collist[listId].Fields[FirstNamePhonetic];
                column3.Hidden = true;
                column3.StaticName = FirstNamePhonetic;
                column3.Update();

                collist[listId].Fields.Add(FullName, SPFieldType.Text, false);
                var column4 = (SPFieldText) collist[listId].Fields[FullName];
                column4.StaticName = FullName;
                column4.Update();

                collist[listId].Fields.Add(UserId, SPFieldType.Guid, false);
                var userId = (SPFieldText)collist[listId].Fields[UserId];
                userId.StaticName = UserId;
                userId.Update();

                collist[listId].Fields.Add(Email, SPFieldType.Text, false);
                var column5 = (SPFieldText) collist[listId].Fields[Email];
                column5.StaticName = Email;                
                column5.Update();

                collist[listId].Fields.Add(Company, SPFieldType.Text, false);
                var column6 = (SPFieldText) collist[listId].Fields[Company];
                column6.StaticName = FullName;
                column6.Update();


                collist[listId].Fields.Add(CompanyPhonetic, SPFieldType.Text, false);
                var column7 = (SPFieldText) collist[listId].Fields[CompanyPhonetic];
                column7.StaticName = FullName;
                column7.Hidden = true;
                column7.Update();

                collist[listId].Fields.Add(JobTitle, SPFieldType.Text, false);
                var column8 = (SPFieldText) collist[listId].Fields[JobTitle];
                column8.StaticName = JobTitle;
                column8.Update();


                collist[listId].Fields.Add(WorkPhone, SPFieldType.Text, false);
                var column9 = (SPFieldText) collist[listId].Fields[WorkPhone];
                column9.StaticName = WorkPhone;                
                column9.Update();

                collist[listId].Fields.Add(HomePhone, SPFieldType.Text, false);
                var column10 = (SPFieldText) collist[listId].Fields[HomePhone];
                column10.StaticName = HomePhone;                
                column10.Update();

                collist[listId].Fields.Add(CellPhone, SPFieldType.Text, false);
                var column11 = (SPFieldText) collist[listId].Fields[CellPhone];
                column11.StaticName = CellPhone;                
                column11.Update();


                collist[listId].Fields.Add(WorkFax, SPFieldType.Text, false);
                var column12 = (SPFieldText) collist[listId].Fields[WorkFax];
                column12.StaticName = WorkFax;                
                column12.Update();

                collist[listId].Fields.Add(WorkAddress, SPFieldType.Text, false);
                var column13 = (SPFieldText) collist[listId].Fields[WorkAddress];
                column13.StaticName = WorkAddress;                
                column13.Update();

                collist[listId].Fields.Add(WorkZip, SPFieldType.Text, false);
                var column14 = (SPFieldText) collist[listId].Fields[WorkZip];
                column14.StaticName = WorkZip;                
                column14.Update();

                collist[listId].Fields.Add(WorkState, SPFieldType.Text, false);
                var column15 = (SPFieldText) collist[listId].Fields[WorkState];
                column15.StaticName = WorkState;
                column15.Update();

                collist[listId].Fields.Add(WorkCity, SPFieldType.Text, false);
                var column16 = (SPFieldText) collist[listId].Fields[WorkCity];
                column16.StaticName = WorkCity;                
                column16.Update();

                collist[listId].Fields.Add(WorkCountry, SPFieldType.Text, false);
                var column17 = (SPFieldText) collist[listId].Fields[WorkCountry];
                column17.StaticName = WorkCountry;
                column17.Update();

                collist[listId].Fields.Add(WebPage, SPFieldType.URL, false);
                var column18 = (SPFieldUrl) collist[listId].Fields[WebPage];
                column18.StaticName = WebPage;
                column18.Update();

                collist[listId].Fields.Add(Comments, SPFieldType.Note, false);
                var column19 = (SPFieldMultiLineText) collist[listId].Fields[Comments];
                column19.StaticName = Comments;
                column19.RichTextMode = SPRichTextMode.FullHtml;
                column19.Update();


                collist[listId].Fields.Add(Password, SPFieldType.Text, true);
                var password = (SPFieldText)collist[listId].Fields[Password];
                password.StaticName = Password;
                password.MaxLength = 20;                                
                password.Update();

                collist[listId].Fields.Add(PasswordQuestion, SPFieldType.Text, false);
                var column21 = (SPFieldText) collist[listId].Fields[PasswordQuestion];
                column21.StaticName = PasswordQuestion;                
                column21.Update();

                
                collist[listId].Fields.Add(PasswordReminderAnswer, SPFieldType.Text, false);
                var column22 = (SPFieldText) collist[listId].Fields[PasswordReminderAnswer];
                column22.StaticName = PasswordReminderAnswer;
                column22.MaxLength = 20;                
                column22.Update();

                collist[listId].Fields.Add(IsApproved, SPFieldType.Boolean, false);
                var column23 = (SPFieldBoolean) collist[listId].Fields[IsApproved];
                column23.StaticName = IsApproved;          
                column23.Update();

                collist[listId].Fields.Add(IsLockedOut, SPFieldType.Boolean, false);
                var column24 = (SPFieldBoolean) collist[listId].Fields[IsLockedOut];
                column24.StaticName = IsLockedOut;                
                column24.Update();

                collist[listId].Fields.Add(LastActivityDate, SPFieldType.DateTime, false);
                var lastActivityDate = (SPFieldDateTime) collist[listId].Fields[LastActivityDate];
                lastActivityDate.StaticName = LastActivityDate;                
                lastActivityDate.Update();

                collist[listId].Fields.Add(LastLockedOutDate, SPFieldType.DateTime, false);
                var lastLockedOutDate = (SPFieldDateTime) collist[listId].Fields[LastLockedOutDate];
                lastLockedOutDate.StaticName = LastLockedOutDate;                
                lastLockedOutDate.Update();

                collist[listId].Fields.Add(LastLoginDate, SPFieldType.DateTime, false);
                var lastLoginDate = (SPFieldDateTime) collist[listId].Fields[LastLoginDate];
                lastLoginDate.StaticName = LastLoginDate;                
                lastLoginDate.Update();

                collist[listId].Fields.Add(LastPasswordChangeDate, SPFieldType.DateTime, false);
                var lastPasswordChangeDate = (SPFieldDateTime) collist[listId].Fields[LastPasswordChangeDate];
                lastPasswordChangeDate.StaticName = LastPasswordChangeDate;                
                lastPasswordChangeDate.Update();

                collist[listId].Fields.Add(CreationDate, SPFieldType.DateTime, false);
                var creationDate = (SPFieldDateTime) collist[listId].Fields[CreationDate];
                creationDate.StaticName = CreationDate;                
                creationDate.Update();

                collist[listId].Fields.Add(Role, SPFieldType.Text, true);
                var role = (SPFieldText) collist[listId].Fields[Role];
                role.StaticName = Role;             
                role.Update();
                
                SPViewCollection viewcoll = collist[listId].Views;
                Guid defaultsguid = collist[listId].Views[0].ID;
                viewcoll.Delete(defaultsguid);
                SPSecurity.RunWithElevatedPrivileges(delegate
                                                         {
                                                             collist[listId].BreakRoleInheritance(false);
                                                             var group = spweb.AssociatedOwnerGroup;
                                                             group.AddUser(spweb.CurrentUser);
                                                             var roleassing = new SPRoleAssignment(group);
                                                             var roledefind = spweb.RoleDefinitions["Full Control"];
                                                             roleassing.RoleDefinitionBindings.Add(roledefind);
                                                             collist[listId].RoleAssignments.Add(roleassing);
                                                             collist[listId].AnonymousPermMask64 |=
                                                                 SPBasePermissions.EmptyMask;
                                                             collist[listId].AllowEveryoneViewItems = false;
                                                             collist[listId].Update();
                                                         });          

                var item = collist[listId].Items.Add();
                item[UserName] = "Administrator";
                item[Email] = "Dzung.nguyenManh@gmail.com";
                item[IsApproved] = "true";
                item[Password] = "M@nhDung";
                item[FullName] = "Quản trị hệ thống";
                item[FirstName] = "Quản trị hệ thống";
                item[CellPhone] = "0989889758";
                item[IsRootAccount] = "true";
                item.Update();
                collist[listId].Update();

            
           
        }
     
        public static void DeleteList(string listId, SPWeb spWeb)
        {
            spWeb.AllowUnsafeUpdates = true;
            spWeb.Lists.Delete(new Guid(listId));
            spWeb.Update();
            spWeb.AllowUnsafeUpdates = false;

        }

        public static void ModifyWebconfig(SPWebApplication application,string featureId)
        {
            
                SPSecurity.RunWithElevatedPrivileges(()=>
               {                                                                                                
                   

                    application.WebConfigModifications.Clear();
                   var modification = new SPWebConfigModification
                                        {
                                            Path = "configuration/system.web",
                                            Name = "membership",
                                            Owner = featureId,
                                            Sequence = 0,
                                            Type =SPWebConfigModification.SPWebConfigModificationType.EnsureSection,
                                            Value = "<membership>"
                                        };
                   application.WebConfigModifications.Add(modification);

                   var configAttribute = new SPWebConfigModification
                                        {

                                            Path = "configuration/system.web/membership",
                                            Name = "defaultProvider",
                                            Owner = featureId,
                                            Sequence = 0,
                                            Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute,
                                            Value = "CsMembership"

                                        };
                   application.WebConfigModifications.Add(configAttribute);
                   var configchildnode = new SPWebConfigModification
                                             {

                                                 Path = "configuration/system.web/membership",
                                                 Name = "providers",
                                                 Owner = featureId,
                                                 Sequence = 0,
                                                 Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
                                                 Value = "<providers></providers>"

                                             };
                    application.WebConfigModifications.Add(configchildnode);

                    var addchildnode = new SPWebConfigModification
                    {

                        Path = "configuration/system.web/membership/providers",
                        Name = "add",
                        Owner = featureId,
                        Sequence = 0,
                        Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
                        Value = "<add enablePasswordRetrieval='false' enablePasswordReset='true' requiresQuestionAndAnswer='false' requiresUniqueEmail='false' passwordFormat='Clear' maxInvalidPasswordAttempts='5' minRequiredPasswordLength='1' minRequiredNonalphanumericCharacters='0'  passwordAttemptWindow='10' masterUserName='admin@tbtsoftware.com' masterUserPassword='ssp@2012' SiteURL='" + application.Sites[0].Url + "' MembershipList='" + ListName + "' userIDFieldName='Email' passwordFieldName='Password' applicationName='/' name='CsMembership' type='ProjectHT.YKDGVB2012.Core.Membership.CsMembershipProvider, ProjectHT.YKDGVB2012.Core.Membership, Version=1.0.0.0, Culture=neutral, PublicKeyToken=69db40eb91817252'/>"

                    };
                    application.WebConfigModifications.Add(addchildnode);

                    application.Update();                   
                    application.WebService.ApplyWebConfigModifications();            
                });                        
          
            

        }

        #endregion

        #region helper





        #endregion


    }
}